package com.library.admin.config;

import cn.hutool.core.util.StrUtil;
import com.library.admin.modules.user.entity.User;
import com.library.admin.modules.user.service.UserService;
import com.library.common.service.TrendInvocationSecurityService;
import com.library.common.service.bo.CurrentLoginUser;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取用户配置
 *
 * @author: xyh
 * @create: 2023-10-04
 **/
@Log4j2
@Configuration
public class UserSecurityConfig {

    @Resource
    private UserService userService;

    @Bean
    public TrendInvocationSecurityService trendInvocationSecurityService() {
        return username -> {
            if (StrUtil.isEmpty(username)) {
                return null;
            }
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return null;
            }
            CurrentLoginUser currentLoginUser = new CurrentLoginUser();
            currentLoginUser.setPhone(user.getPhone());
            currentLoginUser.setUserId(user.getId());
            currentLoginUser.setUsername(user.getUsername());
            currentLoginUser.setRealName(user.getRealName());
            currentLoginUser.setJobNumber(user.getJobNumber());
            if (StrUtil.isNotEmpty(user.getRoleIds())) {
                List<String> roleIds = Arrays.asList(user.getRoleIds().split(","));
                currentLoginUser.setRoleIds(roleIds.stream().map(Integer::parseInt).collect(Collectors.toList()));
            }
            return currentLoginUser;
        };
    }
}

